package com.yc.web.servlets;

import com.yc.DAO.UserDAO;
import com.yc.bean.Resuser;
import com.yc.model.JsonModel;
import com.yc.utils.EncryptUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.security.NoSuchAlgorithmException;
import java.util.IdentityHashMap;
import java.util.List;

/**
 * @author zwei
 * @create 2024-06-08 19:42
 */
@WebServlet("/user.action")
public class UserServlet extends BaseServlet {
    public void checkLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        JsonModel jm = new JsonModel();
        HttpSession session = req.getSession();
        if (session.getAttribute("resuser") != null) {
            jm.setCode(1);
            Resuser resuser = (Resuser) session.getAttribute("resuser");
            resuser.setPwd("别偷看！");
            jm.setObj(resuser);
        } else {
            jm.setCode(0);
        }
        super.writeJson(jm, resp);
    }

    public void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        JsonModel jm = new JsonModel();
        HttpSession session = req.getSession();
        session.removeAttribute("resuser");
        jm.setCode(1);
        super.writeJson(jm, resp);
    }

    public void login(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, InstantiationException, IllegalAccessException, IOException, NoSuchAlgorithmException {
        JsonModel jm = new JsonModel();
        //取出session中的验证码
        HttpSession session = req.getSession();
        String code = (String) session.getAttribute("code");
        Resuser resuser = super.parseObjectFromRequest(req, Resuser.class);
        String yzm = req.getParameter("yzm");//获取用户输入的验证码
        //验证码判断
        if (!code.equals(yzm)) {
            jm.setCode(0);
            jm.setError("验证码错误");
            super.writeJson(jm, resp);
            return;
        }
        //对用户输入的密码进行加密
        resuser.setPwd(EncryptUtils.encryptToMD5(EncryptUtils.encryptToMD5(resuser.getPwd())));
        UserDAO userDAO = new UserDAO();
        List<Resuser> list = userDAO.finduser(resuser.getUsername(), resuser.getPwd());
        if (list != null && list.size() > 0) {
            Resuser rs = list.get(0);
            rs.setPwd("别偷看！");
            jm.setCode(1);
            jm.setObj(rs);
            //登录的信息记录到session中
            session.setAttribute("resuser", rs);
        } else {
            jm.setCode(0);
            jm.setError("用户名或者密码错误，请重新输入");
        }
        super.writeJson(jm, resp);
    }
}
